package com.ruoyi.common.utils;

import cn.hutool.core.util.StrUtil;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.DingTalkClient;
import com.dingtalk.api.request.OapiRobotSendRequest;
import com.dingtalk.api.response.OapiRobotSendResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.binary.Base64;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * 钉钉消息工具类
 *
 * @author Lorry
 * @description
 * @since 2021-09-30 18:41
 */
@Slf4j
public class DingUtil {
    //文本消息
    private static final String TEXT = "text";
    private static final String LINK = "link";
    private static final String MARKDOWN = "markdown";
    private static final String ACTION_CARD = "actionCard";
    private static final String FEED_CARD = "feedCard";

    private static final String SERVER_URL = "https://oapi.dingtalk" +
            ".com/robot/send?access_token=d34583194d9fc3efac03fef801ecd552df8669643521d5009b55b40c8e430ade";
    private static final String SECRET = "SECe81e821019331f3db62456f4bc0ebd6451df2441148c78272ba87b24255215bb";


    /**
     * 推送消息
     *
     * @param msg
     * @return
     */
    public static OapiRobotSendResponse sendMessage(DingMsgBean msg) {
        OapiRobotSendResponse response = null;
        try {
            // log.debug("开始推送钉钉消息：" + JSON.toJSONString(msg));
            Long timestamp = System.currentTimeMillis();
            String secret = SECRET;

            String stringToSign = timestamp + "\n" + secret;
            Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(new SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256"));
            byte[] signData = mac.doFinal(stringToSign.getBytes(StandardCharsets.UTF_8));
            String sign = URLEncoder.encode(new String(Base64.encodeBase64(signData)), "UTF-8");

            DingTalkClient client = new DefaultDingTalkClient(SERVER_URL + "&timestamp=" + timestamp + "&sign=" + sign);
            OapiRobotSendRequest request = new OapiRobotSendRequest();

            OapiRobotSendRequest.At at = new OapiRobotSendRequest.At();
            if (msg.isAtAll() || msg.getMobileList() == null || msg.getMobileList().size() == 0) {
                //推送所有人
                at.setIsAtAll(true);
            } else {
                //推送指定用户
                at.setAtMobiles(msg.getMobileList());
                at.setIsAtAll(false);
            }
            request.setAt(at);

            //文本消息
            if (TEXT.equals(msg.getMsgType())) {
                request.setMsgtype(TEXT);
                OapiRobotSendRequest.Text text = new OapiRobotSendRequest.Text();
                text.setContent(msg.getText());
                request.setText(text);
            } else if (MARKDOWN.equals(msg.getMsgType())) {
                request.setMsgtype(MARKDOWN);
                OapiRobotSendRequest.Markdown markdown = new OapiRobotSendRequest.Markdown();
                markdown.setTitle(msg.getTitle());
                markdown.setText(msg.getText());
                request.setMarkdown(markdown);
            }

            response = client.execute(request);
            // log.debug("钉钉推送返回结果：" + JSON.toJSONString(response));
        } catch (Exception e) {
            log.error("sendMessage exception!", e);
        }

        return response;
    }

    public static void sendText(String text) {
        List<String> mobileList = new ArrayList<>();

        DingMsgBean msg = new DingMsgBean();
        msg.setMsgType(TEXT);
        msg.setMobileList(mobileList);
        msg.setText(text);
        msg.setAtAll(true);

        sendMessage(msg);
    }

    public static void sendMarkdown(String title, String text) {
        List<String> mobileList = new ArrayList<>();

        DingMsgBean msg = new DingMsgBean();
        msg.setMsgType(MARKDOWN);
        msg.setTitle(title);
        msg.setText(text);
        msg.setMobileList(mobileList);
        msg.setAtAll(true);

        sendMessage(msg);
    }

    public static void main(String[] args) throws Exception {
       sendText("桃花坞里桃花庵，桃花庵下桃花仙！");
        String text = StrUtil.format("### 订单信息\n>- UserId: {}\n>- Name: {}\n>- 金额：${}\n>- productId: {}\n>- " +
                "订单校验状态：{}", 10086, "xiolo@gmail.com", 29.99, "8000coins", "ok");
        DingUtil.sendMarkdown("订单来了！", text);

        int listSize = 21,coolPoolSize=5;
        int size = listSize < coolPoolSize ? listSize : (int) Math.ceil(listSize * 1.0 / coolPoolSize);
        System.out.println("size = " + size);
    }
}

